package cn.swh.guguanjia.interceptor;

import cn.swh.guguanjia.entity.SysResource;
import cn.swh.guguanjia.service.SysResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author: swh
 * @Description:
 * @Date: 2020/11/6 16:25
 * @Version: 1.0
 */

@Component
public class ResourceInterceptor implements HandlerInterceptor {

    @Autowired
    SysResourceService sysResourceService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        List<SysResource> sysResources = sysResourceService.selectResources();
        //获取路径
        String url = request.getRequestURI();
        //转换/重新给url赋值
        url = url.replace(request.getContextPath() + "/", "");

        boolean noed=false;
        //遍历
        for (SysResource sysResource : sysResources) {
            //判断路径是否相同
            if(sysResource.getUrl().equals(url)){
                noed=true;
                break;
            }
        }

        if(noed){
            //需要授权判断
            List<SysResource> resources = (List<SysResource>) request.getSession().getAttribute("resources");
            for (SysResource resource : resources) {
                if(resource.getUrl().equals(url)){
                    return true;
                }
            }

            //需要授权直接跳转授权页面
            response.sendRedirect(request.getContextPath()+"/notauth.html");
            return false;
        }

        return true;
    }
}
